/**
 * @Author:Geln Yang
 * @Created:2008-7-27 $ Revision: 1.0 $ $ Author: Geln Yang $ $ Date: 2008-7-27 $
 */
package org.geln.web.webwork.interceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geln.web.Constants;
import org.geln.web.container.Application;
import org.geln.web.context.ISessionContext;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.Interceptor;

/**
 * @Author:Geln Yang
 * @Created:2008-7-27
 */
public class SessionContextInterceptor implements Interceptor {
	private static final Log log = LogFactory.getLog(SessionContextInterceptor.class);

	public static final String SessionContext = "sessionContext";

	private static final String BIND_FLAG = "_session_bind_flag_";

	public void destroy() {
	}

	public void init() {
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		String bind_flag = (String) ActionContext.getContext().get(BIND_FLAG);
		if ("true".equals(bind_flag)) {
			return invocation.invoke();
		}
		String account = (String) ActionContext.getContext().getSession().get(Constants.ACCOUNT);
		ISessionContext context = (ISessionContext) Application.getComponent(SessionContextInterceptor.SessionContext);
		try {
			context.bindResource(ISessionContext.ACCOUNT, account);
			context.bindResource(ISessionContext.REMOTE_HOST, ServletActionContext.getRequest().getRemoteAddr());
			context
					.bindResource(ISessionContext.HTTP_SESSIONID, ServletActionContext.getRequest().getSession()
							.getId());
			context.bindResource(ISessionContext.LOCALE, ActionContext.getContext().getLocale());
			ActionContext.getContext().put(BIND_FLAG, "true");
			return invocation.invoke();
		} finally {
			try {
				context.unbindResource(ISessionContext.ACCOUNT);
				context.unbindResource(ISessionContext.REMOTE_HOST);
				context.unbindResource(ISessionContext.HTTP_SESSIONID);
				context.unbindResource(ISessionContext.LOCALE);
				ActionContext.getContext().put(BIND_FLAG, "false");
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
	}

}
